#include "StdAfx.h"
#include "decisionTreeParser.h"
#include <sstream>
#include "hugin"
#include <iostream>
#include "ExpandTimeSteps.h"

//////////////////////////////////////////////////////////////////////////
//Author	:	Ross Conroy	ross.conroy@tees.ac.uk
//Date		:	06/05/2014
//
//This class uses time step information and current observation
//to determine that action the agent should take.
//////////////////////////////////////////////////////////////////////////

decisionTreeParser::decisionTreeParser(void)
{
	//_spuSolver = new SinglePolicyUpdateSolver("C:\\Nets\\lv0D.net");
	//Domain * domain = _spuSolver->GetDomain();

	ParseListener *pl = new DefaultParseListener();
	Domain * domain = new Domain("C:\\Nets\\lv0A.net", pl);
	ExpandTimeSteps expand;
	domain = expand.Expand(domain, 50, ExpandTimeSteps::IdType::DID);

	_spuSolver = new SinglePolicyUpdateSolver(domain);
}

//uses a decision tree stored in memory to get the decision for the current observation and time step
std::string decisionTreeParser::DecisionFromObservation(int timeStep, std::string observation)
{
	//Insert evidence
	string oNodeName = "oSeeEnemy";

	stringstream ss1;
	ss1 << oNodeName << timeStep;
	oNodeName = ss1.str();

	//cout << oNodeName << endl;

	_spuSolver->InsertEvidence(oNodeName, timeStep, observation);
	//Domain * domain = _spuSolver->solve();

	//find decision node to determine what action to take
	string dNodeName = "a";
	stringstream ss2;
	ss2 << dNodeName << timeStep;

	Domain * domain = _spuSolver->GetDomain();
	DiscreteDecisionNode * node = (DiscreteDecisionNode*)domain->getNodeByName(ss2.str());

	int highestPtr = 0;
	double highestUtil = node->getExpectedUtility(0);

	for(int i = 0; i < node->getNumberOfStates(); i++)
	{
		if(node->getBelief(i) > highestUtil)
		{
			highestUtil = node->getExpectedUtility(i);
			highestPtr = i;
		}
	}

	//Finally enter action taken as evidence
	_spuSolver->InsertEvidence(node, highestPtr);

	return node->getStateLabel(highestPtr);

	//return "Attack";
	//return "Escape";


	return "ERROR";
}